import { login, logout, getInfo } from '@/api/login'
import { setToken, getToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: null,
    name: '',
    avatar: '',
    roles: [],
    perms: '',
    menu: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMS: (state, perms) => {
      state.perms = perms
    },
    SET_MENU: (state, router) => {
      state.menu = router
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.captcha).then(response => {
          const user = response.data
          const roles = response.extra.roles
          const router = response.extra.router
          const perms = response.extra.perms
          console.log(perms)
          setToken(user)
          commit('SET_ROLES', roles)
          commit('SET_NAME', user.username)
          commit('SET_MENU', router)
          commit('SET_PERMS', perms)
          // commit('SET_AVATAR', data.avatar)
          commit('SET_TOKEN', user)
          resolve()
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },

    // 获取用户信息
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        // getInfo(state.token).then(response => {
        getInfo().then(response => {
          console.log(response)
          const data = response.data
          const extra = response.extra
          if (extra.roles && extra.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', extra.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.username)
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        // logout(state.token).then(() => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
